package com.kevin.nettyrpcprovider.server;

import com.kevin.nettyrpcprovider.handler.RpcServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author LXL
 * @Date 2021/9/28 9:36
 **/
@Service
public class RpcServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;

    @Autowired
    private RpcServerHandler rpcServerHandler;

    public void startServer(String ip, int port){
        try{

            //创建线程组
            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup();
            //创建服务端启动助手
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置擦书
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //添加业务处理类
                            pipeline.addLast(rpcServerHandler);
                        }
                    });
            ChannelFuture future = bootstrap.bind(ip, port).sync();
            System.out.println("----------服务端启动成功--------");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (bossGroup != null){
                bossGroup.shutdownGracefully();
            }
            if (workGroup != null){
                workGroup.shutdownGracefully();
            }
        }




    }


    @Override
    public void destroy() throws Exception {
        if (bossGroup != null){
            bossGroup.shutdownGracefully();
        }
        if (workGroup != null){
            workGroup.shutdownGracefully();
        }
    }
}
